import Taro, { switchTab, navigateTo } from '@tarojs/taro'
import { View, ScrollView, Button, Block } from '@tarojs/components'
import {AtIcon, AtButton, AtAccordion, AtCard} from 'taro-ui'
import React, { useState, useEffect } from 'react'

import api from '../../utils/api'
import { formatTime } from '../../utils/formatTime'
import { useAsyncEffect } from '../../utils/index'

import './index.less'
import request from '../../utils/request'

function Task() {
  const [taskList, setTaskList] = useState([])
  const [currentActive, setCurrentActive] = useState(-1)
  const getList = () => {
    request(api.taskList, 'GET', {
      page_size: 100
    }).then(res => {
      setTaskList(res.tasks)
      if (res.tasks.length >= 1) {
        setCurrentActive(0)
      }
    }).catch(res => {
      setTimeout(function () {
        getList()
      }, 1500)
    })
  }
  useEffect(() => {
    getList()
  }, [])


  const handleClick = (i) => {
    setCurrentActive(i)
  }

  const openDialog = (item) => {
    console.log(!!item)
  }
  const receiveTask = (item) => {
    request(api.receiveTask, 'POST', {
      task_id: item.id
    }).then(res => {
      Taro.showToast({
        title: '接受成功',
        icon: 'none'
      })
    })
  }


  return (
    <View className='record'>
      <ScrollView lowerThreshold={100}>
        <View className="task_group">
          {taskList.map((item, index) => {
            return <AtCard
              key={item.id}
              title={item.company.title}
            >
              {item.company_task.map((task, idx) => {
                return <AtAccordion
                  key={task.id}
                  open={currentActive === idx}
                  onClick={handleClick.bind(this, idx)}
                  title={task.title}
                >
                <View className="task_item">
                    <View className="task_info">
                      <View>结算方式:  {task.settle_type == 1 ? '面议' : '计件' }</View>
                      <View>任务内容: {task.content}</View>
                      <View>发布时间: {task.created_at}</View>
                      <AtButton onClick={receiveTask.bind(this, task)} className="task_btn">接受任务</AtButton>
                    </View>
                </View>
                </AtAccordion>
              })}
            </AtCard>
          })}
        </View>
      </ScrollView>
    </View>
  )
}

export default Task
